<template>
  <div class="container">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" @submit.prevent :status-icon="true" size="large">
      <el-form-item label="账号" prop="account">
        <el-input v-model="ruleForm.account"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" @keyup.enter="submitForm(ruleFormRef)"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">立即注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElForm, ElNotification } from 'element-plus'
import { register } from '../api/index'
import { useRouter } from 'vue-router'
type FormInstance = InstanceType<typeof ElForm>
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  account: '' as string,
  password: '' as string,
})
const router = useRouter()
const rules = reactive({
  account: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'change',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'change',
    },
  ],
})
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log(ruleForm.account, ruleForm.password)
      register(ruleForm.account, ruleForm.password)
        .then((res) => {
          console.log(res)
          if (res.data.isExist) {
            ruleForm.account = null
            ruleForm.password = null
            ElNotification({
              title: '失败了~',
              message: res.data.msg,
              position: 'bottom-right',
              type: 'warning',
              duration: 2000,
            })
          } else {
            ElNotification({
              title: '2s后跳转登录页',
              message: res.data.msg,
              position: 'bottom-right',
              type: 'success',
              duration: 2000,
            })
            setTimeout(() => {
              router.push('/login')
            }, 2000)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      console.log('error submit!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  background: url(../assets/bg.jpg) no-repeat;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  .el-form {
    transform: translateX(-25%);
  }
}
.el-input {
  width: 15rem;
}
</style>